# -*- coding: utf-8 -*-
import paramiko, time

def ssh_connect(ip, username, passwd, port):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, port, username, passwd, timeout=5)
        print '%s\tOK\n' % (ip)
        return ssh
    except:
        print '%s\tError\n' % (ip)


def get_cycle_channel(ssh):
    channel = ssh.invoke_shell()
    out = channel.recv(9999)
    print(out.decode("ascii"))
    return channel

def run_cycle_cmd(channel, cmd):
    # channel.send('cd /usr/local\n')
    # channel.send('ls\n')

    channel.send(cmd + '\n')
    while not channel.recv_ready():
        time.sleep(3)

    out = channel.recv(9999)
    return out.decode("ascii")

    # channel.send('mysql -uroot -piWill220182@\n')
    # while not channel.recv_ready():
    #     time.sleep(3)
    # out = channel.recv(9999)
    # print(out.decode("ascii"))

def run_cmd(ssh, cmd):
    try:
        stdin, stdout, stderr = ssh.exec_command(cmd)
        # 屏幕输出
        print(stdout.read())
        """
        out = stdout.readlines()
        for o in out:
            print o,
        """
    except:
        print '\tError\n'

# 连接mysql
#run_cmd(ssh, 'ls -ll')
#run_cmd(ssh, 'cd /usr/local;pwd;ls -ll')
#run_cmd(ssh, "mysql -uroot -piWill220182@ -Drenren_fast -e 'select * from sys_role_menu'")